package com.lanou.dllo.vc.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.ImageMessageBody;
import com.easemob.chat.LocationMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VoiceMessageBody;
import com.easemob.util.PathUtil;
import com.lanou.dllo.vc.MyApplication;
import com.lanou.dllo.vc.R;
import com.lanou.dllo.vc.adapter.CallBackSmeil;
import com.lanou.dllo.vc.adapter.ChatAdapter;
import com.lanou.dllo.vc.adapter.EmotionAdapter;
import com.lanou.dllo.vc.adapter.GridViewAdapter;
import com.lanou.dllo.vc.greendao.ChatMessage;
import com.lanou.dllo.vc.view.EmotionGridview;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by dllo on 15/12/2.
 */
public class ChatGroupActivity extends BaseActivity implements View.OnClickListener, CallBackSmeil, View.OnTouchListener {


    private List<View> gridviews;
    private List<String> emolist;
    private EmotionAdapter emoAdapeter;
    private EmotionGridview emo_gridview;
    private GridViewAdapter gridviewAdapter;
    private File myRecAudioFile, cameraFile;
    private MyApplication myApplication;
    private String url;
    private boolean sdCardExit;
    private MediaRecorder mediaRecorder;
    private AnimationDrawable animationDrawable;

    private ChatMessage chatMessage;


    @Bind(R.id.chat_user)
    TextView group_title;//群名称
    @Bind(R.id.container_to_group)
    ImageView container_to_group;
    @Bind(R.id.container_voide_call)
    LinearLayout container_video_call;
    @Bind(R.id.container_voice_call)
    LinearLayout container_voice_call;
    @Bind(R.id.et_sendmessage)
    EditText et_sendmessage;
    @Bind(R.id.iv_emoticons_normal)
    ImageView emoImg;
    @Bind(R.id.iv_emoticons_checked)
    ImageView iv_emoticons_checked;
    @Bind(R.id.more)
    LinearLayout more;
    @Bind(R.id.ll_btn_container)
    LinearLayout ll_btn_container;
    @Bind(R.id.ll_face_container)
    LinearLayout ll_face_container;
    @Bind(R.id.btn_press_to_speak)
    LinearLayout btn_press_to_speak;
    @Bind(R.id.edittext_layout)
    RelativeLayout edittext_layout;
    @Bind(R.id.btn_set_mode_keyboard)
    Button btn_set_mode_keyboard;
    @Bind(R.id.btn_set_mode_voice)
    Button recordingBtn;
    @Bind(R.id.speakTv)
    TextView speakTv;
    @Bind(R.id.recording_container)
    RelativeLayout recording_container;
    @Bind(R.id.mic_image)
    ImageView mic_image;
    @Bind(R.id.vPager)
    ViewPager vPager;
    @Bind(R.id.btn_more)
    Button btn_more;
    @Bind(R.id.btn_send)
    Button btn_send;
    @Bind(R.id.list)
    ListView list;
    private String groudId,chatCon;
    private List<ChatMessage> chat_con;
    private ChatAdapter adapter;
    private EMMessage message;
    private Handler handler;
    private int count = 0, len;

    @Override
    protected int getLayout() {
        return R.layout.activity_chat;
    }

    @Override
    protected void initView() {

        ButterKnife.bind(this);

        et_sendmessage.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (et_sendmessage.getText().toString() != null && et_sendmessage.getText().toString().length() > 0) {
                    btn_more.setVisibility(View.GONE);
                    btn_send.setVisibility(View.VISIBLE);
                } else {
                    btn_more.setVisibility(View.VISIBLE);
                    btn_send.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        btn_send.setOnClickListener(this);
        chat_con = new ArrayList<>();
        adapter = new ChatAdapter(this);
        list.setAdapter(adapter);
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                adapter.addData(chat_con);
                return false;
            }
        });
        //表情初始化

        emoImg.setOnClickListener(this);

        iv_emoticons_checked.setOnClickListener(this);
        vPager = (ViewPager) findViewById(R.id.vPager);


        //viewpage  初始化数据
        gridviews = new ArrayList<View>();
        //表情list
        emolist = getEmotionList(35);
        View gr1 = getGridChildView(1);
        View gr2 = getGridChildView(2);
        gridviews.add(gr1);
        gridviews.add(gr2);
        emoAdapeter = new EmotionAdapter(gridviews);

        vPager.setAdapter(emoAdapeter);

        btn_press_to_speak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        btn_press_to_speak.setOnTouchListener(this);
        /* 判断SD Card是否插入 */
        sdCardExit = Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED);

        container_to_group.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            groudId = intent.getStringExtra("group");
            group_title.setText(groudId);
        }
        //隐藏软键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        接收消息:
        EMChatManager.getInstance().registerEventListener(new EMEventListener() {

            @Override
            public void onEvent(EMNotifierEvent event) {
                // TODO Auto-generated method stub
                message = (EMMessage) event.getData();
                //                ((EMMessage) event.getData()).getBody()这个返回的是文本信息
                //                ((EMMessage) event.getData()).getFrom()这个是发送人
                //                ((EMMessage) event.getData()).getTo()这个是接收人
                Log.i("lanou", "==========>收到新消息" + ((EMMessage) event.getData()).getFrom());

                if (String.valueOf(((EMMessage) event.getData()).getTo()).equals(groudId)) {

                    chatCon = String.valueOf(((EMMessage) event.getData()).getBody());
                    Log.i("lanou", "----------->保存聊天" + chatCon);
                    Log.i("lanou", "----------->保存聊天" + String.valueOf(((EMMessage) event.getData()).getType()));

                    if (String.valueOf(((EMMessage) event.getData()).getType()).equals("IMAGE")) {
                        String[] str = chatCon.split("thumbnial:");
                        Log.i("lanou", "" + str[str.length - 1]);
                        chatCon = str[str.length - 1];
                    }
                    chatMessage = new ChatMessage();
                    chatMessage.setFromUsre_Con(chatCon);
                    chat_con.add(chatMessage);
                    handler.sendEmptyMessage(10);


                    Log.i("lanou", "zhejlj_________________");
                } else {
                    Log.i("lanou", "---------asda--->");
                }

            }
        }, new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewMessage});

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case  R.id.btn_send:
                send();
                break;

            case R.id.iv_emoticons_normal:
                //发送表情:
                displayEmo();
                break;
            case R.id.iv_emoticons_checked://表情按钮被点击
                emoImg.setVisibility(View.VISIBLE);
                iv_emoticons_checked.setVisibility(View.GONE);
                more.setVisibility(View.GONE);
                break;
            case R.id.btn_take_picture://拍照功能
                takePicture();
                break;
            case R.id.container_to_group:
                Intent  intent = new Intent(this,GroupDescActivity.class);
                intent.putExtra("groupID",groudId);
                startActivityForResult(intent,25);
                break;

        }
    }

    private void displayEmo() {
        emoImg.setVisibility(View.INVISIBLE);
        ll_btn_container.setVisibility(View.GONE);
        iv_emoticons_checked.setVisibility(View.VISIBLE);
        more.setVisibility(View.VISIBLE);
    }

    //发送信息
    private void send() {
        String charString = et_sendmessage.getText().toString();
        if (charString != null) {
            //
            et_sendmessage.setText("");

            chatMessage = new ChatMessage();
            chatMessage.setToUsre_Con(charString);
            chat_con.add(chatMessage);
            Log.i("lanou", chat_con + "____.");
            adapter.addData(chat_con);


            ////添加到服务器

            EMConversation conversation = EMChatManager.getInstance().getConversation(groudId);
            Log.i("lanou", groudId + "群组名");
            EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
            //如果是群聊，设置chattype,默认是单聊
            message.setChatType(EMMessage.ChatType.GroupChat);
            TextMessageBody txtBody = new TextMessageBody(charString);
            message.addBody(txtBody);

            message.setReceipt(groudId);
            conversation.addMessage(message);
            EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
                @Override
                public void onSuccess() {
                    Log.i("lanouqqqq", "发送成功");
                }

                @Override
                public void onError(int i, String s) {
                    Log.i("lanou", "发送失败");
                }

                @Override
                public void onProgress(int i, String s) {

                }
            });


        }
    }

    private View getGridChildView(int i) {
        View view = View.inflate(this, R.layout.item_emo_gridview, null);
        emo_gridview = (EmotionGridview) view.findViewById(R.id.emo_gridview);
        List<String> list = new ArrayList<String>();
        if (i == 1) {
            List<String> list1 = emolist.subList(0, 20);
            Log.i("lanou", emolist.get(3) + "emotion的第三个图片的名字");
            list.addAll(list1);
        } else if (i == 2) {
            list.addAll(emolist.subList(20, emolist.size()));
        }
        list.add("delete_expression");
        gridviewAdapter = new GridViewAdapter(this, list);
        Log.i("lanou", list + "表情列表");

        emo_gridview.setAdapter(gridviewAdapter);

        gridviewAdapter.setCallBackSmeil(this);

        return view;
    }

    @Override
    public void getEmotion(String emoname) {
        Log.i("lanou", "表情图片" + emoname);
        String emotions = emoname;
        int resId = getResources().getIdentifier(emotions, "mipmap", getPackageName());
        Bitmap bitmap = null;
        bitmap = BitmapFactory.decodeResource(getResources(), resId);
        ImageSpan imageSpan = new ImageSpan(ChatGroupActivity.this, bitmap);

        SpannableString spannableString =
                new SpannableString(emotions);

        spannableString.setSpan(imageSpan, 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (emotions != "delete_expression") {
            et_sendmessage.append(spannableString);
        }
        if (emotions == "delete_expression" && et_sendmessage.getText().length() >= 5) {
            String readySend = et_sendmessage.getText().toString();
            int sendLen = et_sendmessage.getText().length() - 5;
            if (sendLen >= 5) {
                String send = readySend.substring(0, sendLen);
                int resId_ready = getResources().getIdentifier(send, "mipmap", getPackageName());
                Bitmap bitmap_ready = BitmapFactory.decodeResource(getResources(), resId_ready);
                ImageSpan span = new ImageSpan(ChatGroupActivity.this, bitmap_ready);
                SpannableString string = new SpannableString(send);
                string.setSpan(span, 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                et_sendmessage.setText(string);
                et_sendmessage.setSelection(et_sendmessage.getText().length());
            } else if (sendLen == 0) {
                et_sendmessage.setText("");
            }

        }
    }


    //获取图片的列表
    private List<String> getEmotionList(int getSum) {

        List<String> emotionlist = new ArrayList<>();
        for (int j = 1; j < 10; j++) {
            String imgname = "ee_0" + j;

            emotionlist.add(imgname);
        }
        for (int i = 10; i <= getSum; i++) {

            String imgname = "ee_" + i;

            emotionlist.add(imgname);
        }
        return emotionlist;


    }


    //点击获取地址的按钮监听

    public void location_onClick(View view) {

        Intent intent = new Intent(ChatGroupActivity.this, ShowMapActivity.class);

        startActivityForResult(intent, 29);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode == 18) { // 发送照片

            sendPicture(cameraFile.getAbsolutePath());
            chatMessage = new ChatMessage();
            chatMessage.setToUsre_Con(cameraFile.getAbsolutePath());
            chat_con.add(chatMessage);
            Log.i("lanou", chat_con + "____.------>");
            adapter.addData(chat_con);

        }

        //发送地图
        else if (requestCode == 29) {

            String address = data.getStringExtra("mylocation");
            double latitude = data.getDoubleExtra("latitude", 0);
            double longitude = data.getDoubleExtra("longitude",0);

            Log.i("lanou0000", address + latitude + longitude);
            if (address != null && address.length() > 0) {
                sendMyLocation(address,longitude,longitude);
            }


        }

    }

    /**
     * 发语音按钮
     */
    public void setModeVoice(View view) {
        more.setVisibility(View.GONE);
        btn_press_to_speak.setVisibility(View.VISIBLE);
        edittext_layout.setVisibility(View.GONE);
        btn_set_mode_keyboard.setVisibility(View.VISIBLE);
        recordingBtn.setVisibility(View.GONE);

    }

    private void sendMyLocation(String location, double latitude,double longitude) {
        EMConversation conversation = EMChatManager.getInstance().getConversation(groudId);
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.LOCATION);
        //        ImageMessageBody body = new ImageMessageBody();
        message.setChatType(EMMessage.ChatType.GroupChat);
        LocationMessageBody body = new LocationMessageBody(location,latitude,longitude);
        //默认超过100k的图片会压缩,发给对方,可以设置成发送原图
        message.addBody(body);
        message.setReceipt(groudId);
        conversation.addMessage(message);

        chatMessage = new ChatMessage();
        chatMessage.setToUsre_Con("location:"+location);
        chat_con.add(chatMessage);
        adapter.addData(chat_con);

        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
            @Override
            public void onSuccess() {
                Log.i("mymap", "发送成功了我的地址");
            }

            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onProgress(int i, String s) {

            }
        });

        setResult(RESULT_OK);
    }

    public void toggleMore(View view) {

        if (count % 2 == 0) {

            more.setVisibility(View.VISIBLE);
            ll_btn_container.setVisibility(View.VISIBLE);
            ll_face_container.setVisibility(View.GONE);
        } else {
            more.setVisibility(View.GONE);
            ll_face_container.setVisibility(View.VISIBLE);
        }
        count++;

    }

    /**
     * 拍照功能
     */
    private void takePicture() {
        //        Intent intent = new Intent(this, CamerActivity.class);
        //        startActivityForResult(intent, 100);

        cameraFile = new File(PathUtil.getInstance().getImagePath(), myApplication.getInstance().getUserName()
                + System.currentTimeMillis() + ".jpg");
        if (!cameraFile.getParentFile().exists())
            cameraFile.getParentFile().mkdirs();
        url = cameraFile.getAbsolutePath();
        Log.i("lanou", url + "发送图片的文件");
        startActivityForResult(
                new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                18);


        Log.i("lanou00", "Uri------------>" + Uri.fromFile(cameraFile));
    }

    private void sendPicture(final String filePath) {
        EMConversation conversation = EMChatManager.getInstance().getConversation(groudId);
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.IMAGE);
        //如果是群聊，设置chattype,默认是单聊
        message.setChatType(EMMessage.ChatType.GroupChat);

        ImageMessageBody body = new ImageMessageBody(new File(filePath));
        // 默认超过100k的图片会压缩后发给对方，可以设置成发送原图
        // body.setSendOriginalImage(true);
        message.addBody(body);
        message.setReceipt(groudId);
        conversation.addMessage(message);
        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
            @Override
            public void onSuccess() {
                Log.i("lanou", "发送成功");
            }

            @Override
            public void onError(int i, String s) {
                Log.i("lanou", "发送失败");
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });

        setResult(RESULT_OK);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (v.getId() == R.id.btn_press_to_speak) {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                Log.i("lanou", "点击－－－－－－－－－－》");
                speakTv.setText("按住录音");
                //                speakTv.setBackgroundResource(android.R.color.holo_red_light);
                recording_container.setVisibility(View.INVISIBLE);
                animationDrawable = (AnimationDrawable) mic_image.getDrawable();
                animationDrawable.stop();
                if (myRecAudioFile != null) {
                    /* 停止录音 */
                    mediaRecorder.stop();
                    mediaRecorder.release();
                    mediaRecorder = null;
                }
                chatMessage = new ChatMessage();
                chatMessage.setToUsre_Con(myRecAudioFile.getAbsolutePath());
                chat_con.add(chatMessage);
                adapter.addData(chat_con);
                message = null;

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        EMConversation conversation = EMChatManager.getInstance().getConversation(groudId);
                        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.VOICE);
                        message.setChatType(EMMessage.ChatType.GroupChat);
                        FileInputStream fis = null;
                        try {
                            fis = new FileInputStream(myRecAudioFile.getAbsolutePath());
                            len = fis.available();
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        Log.i("lanou","voice发送-------"+myRecAudioFile.getAbsolutePath());
                        VoiceMessageBody body = new VoiceMessageBody(new File(myRecAudioFile.getAbsolutePath()), len);
                        message.addBody(body);
                        message.setReceipt(groudId);
                        conversation.addMessage(message);


                        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
                            @Override
                            public void onSuccess() {
                                Log.i("lanou","-------voice------->发送成功");
                            }

                            @Override
                            public void onError(int i, String s) {
                                Log.i("lanou","-------voice------->发送失败");
                            }

                            @Override
                            public void onProgress(int i, String s) {

                            }
                        });
                    }
                }).start();

            }
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                speakTv.setText("松手结束");

                recording_container.setVisibility(View.VISIBLE);
                mic_image.setImageResource(R.drawable.record_animation);
                animationDrawable = (AnimationDrawable) mic_image.getDrawable();
                animationDrawable.start();
                //                speakTv.setBackgroundResource(android.R.color.holo_red_dark);
                if (myRecAudioFile != null) {
                    /* 停止录音 */
                    myRecAudioFile = null;
                }
                try {
                    initializeAudio();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return false;
    }

    /**
     * 录音初始化
     * @throws IOException
     */
    private void initializeAudio() throws IOException {
        {
            try {
                if (!sdCardExit) {
                    Toast.makeText(ChatGroupActivity.this, "请插入SD Card", Toast.LENGTH_LONG).show();
                    return;
                }
                myRecAudioFile = new File(PathUtil.getInstance().getVoicePath(), myApplication.getInstance().getUserName()
                        + System.currentTimeMillis() + ".mp3");
                if (!myRecAudioFile.getParentFile().exists())
                    myRecAudioFile.getParentFile().mkdirs();


                mediaRecorder = new MediaRecorder();
                /* 设置录音来源为麦克风 */
                mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
                mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);//文件保存位置
                mediaRecorder.setOutputFile(myRecAudioFile.getAbsolutePath());
                mediaRecorder.prepare();
                mediaRecorder.start();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
}
